// mela onlie 购物车界面 订制
import { PureComponent } from "react";
import { Button, Modal } from "antd-mobile"
import { connect } from 'dva';
import { ActivityIndicator } from 'antd-mobile';
import { handleImg, goToPage } from "../../utils/helper";
import { InputItem } from 'antd-mobile';
import { isNull } from '../../utils/helper';
import MToast from '../../components/Util/MToast';
@connect(() => {
  return ({

  })
})
export default class Cart extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      cartItems: [],
      currentItem_id: -1,
      currentQuantity: 20
    }
  }
  componentWillMount() {
    let { dispatch, location } = this.props;
    dispatch({
      type: "global/setHeaderTitle",
      payload: {
        title: T("Shopping cart"),
        path: location.pathname + location.search
      }
    });

    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/list",
          params: [
            // {
            //   key: "a",
            //   value: "11"
            // }
          ]
        },
        callback: (result) => {
          let { data } = result;
          this.setState({
            loading: false,
            cartItems: data.cart_items
          })
        }
      }
    })
    return;
    setTimeout(() => {
      this.setState({
        loading: false,
        cartItems: [
          {
            item_id: 1,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 2,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 3,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 4,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 5,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 6,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 7,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 8,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }, {
            item_id: 9,
            img_url: "http://api.ab.appbuilder.saas.upos.it//public/uploads//upos_melarossa/20200303/95f1_2b19_1583239655234.jpg",
            goods_name: "dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用dell 笔记本电脑，韩国KN94口罩医用",
            goods_id: 10,
            price: 20.99,
            quantity: 2,
            member_nickname: ""
          }

        ]
      })
    }, 1000);
    return;
  }
  componentDidMount() {

  }
  renderList() {
    let { cartItems } = this.state;
    if (!cartItems || cartItems.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T("No products")}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div>
          <div style={{ padding: "10px", fontSize: "16px", borderBottom: "1px solid #ddd", wordBreak: "break-all", lineHeight: 2 }} className="ellipsis1">
            {localStorage[MI_APP_CODE + "name"]}
          </div>
          <div>
            {
              cartItems.map((i, k) => {
                let { img_url, goods_name, price, quantity, item_id } = i;
                return (
                  <div key={k} data-flex="cross:center box:last" style={{ padding: "10px", borderBottom: "1px solid #ddd" }}>
                    <div data-flex="cross:center">
                      <div data-flex="cross:center">
                        <img src={handleImg(img_url)} alt="" style={{ width: "40px", marginRight: "10px" }} />
                      </div>
                      <div>
                        <div className="ellipsis2">
                          {goods_name}
                        </div>
                        <div style={{ color: "red", marginTop: "10px" }}>
                          € {price} x {quantity}
                        </div>
                      </div>
                    </div>

                    <div onClick={() => {
                      this.setState({
                        visible: true,
                        currentItem_id: item_id,
                        currentQuantity: quantity
                      })
                    }}>
                      <img src="image/cart_edit.png" alt="" style={{ width: "40px", marginLeft: "10px" }} />
                    </div>
                  </div>
                )
              })
            }
          </div>
        </div>
      )
    }
  }
  onChange = (val) => {
    console.log(val);
    let value = val;
    const reg1 = /^[0-9]{1,}.{0,1}([0-9]*)?$/;
    const reg = /^(([0-9]{0,})|([0-9]{1,}.{0,1}))([0-9]*)?$/;//匹配 - 号开头的数
    if ((reg.test(value)) || (reg1.test(value)) || value === '') {
      if (value.toString().indexOf(".") == value.length - 1) {
      }
      else if (value.toString().indexOf("-") == 0) {
        if (!isNaN(parseFloat(value))) {
          if (parseFloat(value) == 0) {

          }
          else {
            value = parseFloat(value)
          }
        }
      }
      else if (isNaN(value)) {
        value = parseFloat(value)
      }
      else {
        // value=Number(value)//会把0.0 设置成0 小数点后的0输不进去
      }
      this.setState({
        quantityValue: value
      })
    }
  };
  deleteCarItem = (item_id) => {
    let { cartItems } = this.state;
    let { dispatch } = this.props;
    let newCarItems = cartItems.filter(i => i.item_id != item_id);
    console.log(newCarItems);
    this.setState({
      cartItems: newCarItems,
      visible: false
    })
    // MToast.info("商品删除成功", 1, null, 0)
    // return;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/delete",
          params: [
            {
              key: "item_id",
              value: item_id
            }
          ]
        },
        callback: (result) => {

        }
      }
    })
  }
  //修改当前state中的购物车数据 掉接口往购物车修改数据  
  changeCartItemNumber = () => {
    let { dispatch } = this.props;
    let { currentItem_id, currentQuantity, cartItems, quantityValue } = this.state;
    console.log(currentItem_id, currentQuantity, cartItems);
    if (isNull(quantityValue) || quantityValue == 0) {
      // 删除商品
      this.deleteCarItem(currentItem_id);
    }
    else {
      let newCarItems = cartItems.map(i => {
        if (i.item_id == currentItem_id) {
          return {
            ...i,
            quantity: quantityValue
          }
        }
        else {
          return {
            ...i
          }
        }
      })
      this.setState({
        cartItems: newCarItems
      })
      dispatch({
        type: "form/query",
        payload: {
          apiInfo: {
            url: "cart/update/quantity",
            params: [
              {
                key: "item_id",
                value: currentItem_id
              },
              {
                key: "quantity",
                value: quantityValue
              }
            ]
          },
          callback: (result) => {

          }
        }
      })
    }
  }
  render() {
    let { dispatch } = this.props;
    let { loading, cartItems, currentQuantity, currentItem_id } = this.state;
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    let totalPrice = 0;
    cartItems && cartItems.map(i => {
      totalPrice += i.price * i.quantity
    })
    return (
      <div className="normal" style={{ background: "#fff", minHeight: "100%" }}>
        <div>
          {this.renderList()}
        </div>
        {
          cartItems && cartItems.length > 0 &&
          <div style={{ height: "50px", position: "fixed", bottom: 0, width: "100%", borderTop: "1px solid #ddd", background: "#fff", padding: "0 10px" }} data-flex="cross:center main:justify">
            <div style={{ fontSize: "16px" }}>
              {T("Subtotal")}: <span style={{ color: "red" }}>€ {totalPrice.toFixed(2)}</span>
            </div>
            <Button size="small" type="primary" style={{ padding: "0 10px", height: "40px", lineHeight: "40px", fontSize: "18px" }} onClick={() => {
              goToPage({ dispatch, config: { url: "/placeOrder" }, isReplace: false })
            }}>{T("Place order")}</Button>
          </div>
        }
        <Modal
          popup
          visible={this.state.visible}
          onClose={() => {
            this.setState({
              visible: false
            })
          }}
          animationType="slide-up"
          afterClose={() => { }}
        >
          <div style={{ padding: "10px" }}>
            <Button onClick={() => { this.setState({ visible2: true, quantityValue: currentQuantity }) }}>{T("Modified quantity")}</Button>
            <Button style={{ margin: "10px 0", color: "red" }} onClick={() => {
              this.deleteCarItem(currentItem_id)
            }}>{T("Delete")}</Button>
            <Button onClick={() => {
              this.setState({
                visible: false
              })
            }}>{T("Cancel")}</Button>
          </div>
        </Modal>
        {
          this.state.visible2 && <Modal
            visible={this.state.visible2}
            transparent
            maskClosable={false}
            title=""
            footer={
              [
                { text: T("Cancel"), onPress: () => { this.setState({ visible2: false }) } },
                {
                  text: T("Ok"), onPress: () => {
                    this.changeCartItemNumber();
                    this.setState({ visible2: false,visible:false })
                  }
                }
              ]
            }
            afterClose={() => { }}
          >
            <div data-flex="box:first cross:center">
              <div style={{ width: "60px" }}>{T("quantity")}：</div>
              <InputItem placeholder="" type="number" onChange={this.onChange} defaultValue={this.state.currentQuantity}></InputItem>
            </div>
          </Modal>
        }

      </div>
    )
  }
}
